/*
* Copyright (C) 2012 Manuel Pérez
*
* This file is part of OpenSudoku.
*
* OpenSudoku is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenSudoku is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenSudoku. If not, see <http://www.gnu.org/licenses/>.
*
*/
package email;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class EmailSendService {
	private static EmailSendService instance = null;

	public static EmailSendService getInstance() {
		if (instance == null) {
			instance = new EmailSendService();
		}
		return instance;
	}

	private Properties properties;
	private Session session;

	private EmailSendService() {
		init();
	}

	private void init() {
		properties = new Properties();
		try {
			properties.load(new FileInputStream("./konfig/email.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}

		session = Session.getDefaultInstance(properties);
		// session.setDebug(true);
	}

	public void sendEmail(String cabecera, String mezu, String to) {
		init();
		try {
			MimeMessage message = new MimeMessage(session);
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(
					to));
			message.setSubject(cabecera);
			message.setText(mezu);
			Transport t = session.getTransport("smtp");
			StringBuffer sb = new StringBuffer(
					properties.getProperty("password"));
			t.connect(properties.getProperty("user"), sb.reverse().toString());
			t.sendMessage(message, message.getAllRecipients());
			t.close();
		} catch (MessagingException me) {
			me.printStackTrace();
		}
	}

}